package com.doom.annotaiontest;

import android.content.Context;
import android.util.Log;

import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;

import com.doom.annotaiontest.ui.main.User;
import com.doom.annotaiontest.ui.main.ViewInject;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static org.junit.Assert.*;

/**
 * Instrumented test, which will execute on an Android device.
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    private static final String TAG = ExampleInstrumentedTest.class.getSimpleName();
    @Test
    public void useAppContext() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
        assertEquals("com.doom.annotaiontest", appContext.getPackageName());
    }


    @Test
    public void annotationTest(){
        Log.d(TAG, "test");

        User user = new User();
        Class userclass = User.class;

        Field namefield = null;
        try {
            namefield = userclass.getDeclaredField("name");
        }catch (NoSuchFieldException e){

        }

        Field agefield = null;
        try {
            agefield = userclass.getDeclaredField("age");
        }catch (NoSuchFieldException e){

        }

        ViewInject viewInject = (ViewInject) userclass.getAnnotation(ViewInject.class);
        if(viewInject != null){
            String name = viewInject.name();
            int age = viewInject.age();

            namefield.setAccessible(true);
            agefield.setAccessible(true);

            try {
                namefield.set(user, name);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            try {
                agefield.set(user, age);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
//        user.dump();
        try {
            Method dumpMethod = userclass.getDeclaredMethod("dump", String.class);
            dumpMethod.setAccessible(true);
            try {
                Object result = dumpMethod.invoke(user, "refect_2_dump");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }
}